package com.ledim.adapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.LedimChannelsActivity;
import com.ledim.activity.LedimTagsActivity;
import com.ledim.bean.LedimCardGroupBean;
import com.ledim.bean.LedimChoiceCardBean;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.DensityUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBaseUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.LedimViewHolder;
import com.letv.android.young.client.R;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by ccx on 16/7/28.
 * 1,首页卡片adapter类
 * 2,用于卡片 2,3,5,6,7  （其中5和7一样 用7）(1和8 是viewpage,4是tag)
 * 3,支持卡片换一换功能
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class CardGroupListAdapter extends CarGroupBaseAdapter {

    private TextView mTitle;
    private ImageView mDrop;
    private SimpleDraweeView mBigImageView;
    private TextView cardgroup_item_title, cardgroup_item_subtitle;
    private int pageIndex;
    private ImageView mGetMore;
    private View ll_card_more, ll_top_bigimage;
    private List<BaseCardItemView> mCardItemViews;
    private View ll_card_list;
    private LedimViewHolder mViewHolder;
    private int mPicHeight;
    private int mPicWith;
    public int INITIAL_NUM = 3;

    public CardGroupListAdapter(Activity activity, LedimCardGroupBean cardGroup) {
        super(activity, cardGroup);
        switch (cardGroup.style) {
            case ConstantUtil.CardGroupStyle.card2:
                mPicWith = (mScreenWith - DensityUtil.dip2px(activity, 10) * 4) / 3;
                mPicHeight = mPicWith * 4 / 3;
                INITIAL_NUM = 3;
                break;
            case ConstantUtil.CardGroupStyle.card3:
                mPicWith = (mScreenWith - DensityUtil.dip2px(activity, 10) * 3) / 2;
                mPicHeight = mPicWith * 9 / 16;
                INITIAL_NUM = 5;
                break;
            case ConstantUtil.CardGroupStyle.card5:
            case ConstantUtil.CardGroupStyle.card7:
                mPicWith = (mScreenWith - DensityUtil.dip2px(activity, 10) * 3) / 2;
                mPicHeight = mPicWith * 9 / 16;
                INITIAL_NUM = 4;
                break;
            case ConstantUtil.CardGroupStyle.card6:
                mPicWith = (mScreenWith - DensityUtil.dip2px(activity, 10) * 2) * 11 / 20;
                mPicHeight = (mScreenWith - DensityUtil.dip2px(activity, 10) * 2) * 5 / 20;
                INITIAL_NUM = 4;
                break;
        }

    }

    public List<BaseCardItemView> initCardViews(LedimViewHolder viewHolder) {
        List<BaseCardItemView> views = new ArrayList<BaseCardItemView>();

        views.add(new BaseCardItemView((SimpleDraweeView) viewHolder.getView(R.id.card_item1_photo), (TextView) viewHolder
                .getView(R.id.card_item1_title), (TextView) viewHolder.getView(R.id.card_item1_subtitle), (TextView) viewHolder
                .getView(R.id.card_item1_rating), (TextView) viewHolder.getView(R.id.card_item1_episodes_count)));
        views.add(new BaseCardItemView((SimpleDraweeView) viewHolder.getView(R.id.card_item2_photo), (TextView) viewHolder
                .getView(R.id.card_item2_title), (TextView) viewHolder.getView(R.id.card_item2_subtitle), (TextView) viewHolder
                .getView(R.id.card_item2_rating), (TextView) viewHolder.getView(R.id.card_item2_episodes_count)));
        views.add(new BaseCardItemView((SimpleDraweeView) viewHolder.getView(R.id.card_item3_photo), (TextView) viewHolder
                .getView(R.id.card_item3_title), (TextView) viewHolder.getView(R.id.card_item3_subtitle), (TextView) viewHolder
                .getView(R.id.card_item3_rating), (TextView) viewHolder.getView(R.id.card_item3_episodes_count)));
        if (getPageSize() == 4) {
            views.add(new BaseCardItemView((SimpleDraweeView) viewHolder.getView(R.id.card_item4_photo), (TextView) viewHolder
                    .getView(R.id.card_item4_title), (TextView) viewHolder.getView(R.id.card_item4_subtitle), (TextView) viewHolder
                    .getView(R.id.card_item4_rating), (TextView) viewHolder.getView(R.id.card_item4_episodes_count)));
        }
        return views;
    }

    /**
     * @return 获取每一页的数据注意 头部是否展示一个card
     */
    public int getPageSize() {
        switch (mCardGroupBean.style) {
            case ConstantUtil.CardGroupStyle.card3:
            case ConstantUtil.CardGroupStyle.card6:
                //卡片组3和6有头部
                return INITIAL_NUM - 1;
            default:
                return INITIAL_NUM;
        }
    }

    public boolean needShowResetDataView(LedimCardGroupBean cardGroup) {
        return cardGroup.cards != null && cardGroup.cards.size() > INITIAL_NUM;
    }

    /**
     * @param cardGroup
     * @return 获取下一页数据
     */
    protected List<LedimChoiceCardBean> getNextPageData(LedimCardGroupBean cardGroup) {
        int pageSize = getPageSize();
        int maxPage;//最大页数
        int start;
        int end;
        if (cardGroup.style == ConstantUtil.CardGroupStyle.card3 ||
                cardGroup.style == ConstantUtil.CardGroupStyle.card6) {
            if (cardGroup.cards.size() <= 1) {
                return null;
            }
            maxPage = ((cardGroup.cards.size() - 1) % pageSize == 0 ? (cardGroup.cards.size() - 1) /
                    pageSize : (cardGroup.cards.size() - 1) / pageSize + 1);//最大页数
            if (pageIndex >= maxPage) {
                pageIndex = pageIndex % maxPage;
            }
            start = pageSize * pageIndex + 1;
            end = (pageIndex + 1) * pageSize + 1;
        } else {
            maxPage = (cardGroup.cards.size() % pageSize == 0 ? cardGroup.cards.size() / pageSize
                                                              : cardGroup.cards.size() / pageSize +
                               1);//最大页数
            if (pageIndex >= maxPage) {
                pageIndex = pageIndex % maxPage;
            }
            start = pageSize * pageIndex;
            end = (pageIndex + 1) * pageSize;
        }

        if (end > cardGroup.cards.size()) {
            end = cardGroup.cards.size();
            List list = new ArrayList();
            list.addAll(cardGroup.cards.subList(start, end));
            if (pageIndex > 0) {
                if (cardGroup.style == ConstantUtil.CardGroupStyle.card3 ||
                        cardGroup.style == ConstantUtil.CardGroupStyle.card6) {

                    list.addAll(cardGroup.cards.subList(1, pageSize - (end - start) + 1));
                } else {

                    list.addAll(cardGroup.cards.subList(0, pageSize - (end - start)));
                }
            }
            return list;
        }
        return cardGroup.cards.subList(start, end);
    }

    public void initView(LedimViewHolder viewHolder) {
        mTitle = viewHolder.getView(R.id.tv_card_title);
        mGetMore = viewHolder.getView(R.id.iv_card_needmore);
        mDrop = viewHolder.getView(R.id.card_style_more_drop);
        mBigImageView = viewHolder.getView(R.id.card_bigimage_photo);
        ll_card_list = viewHolder.getView(R.id.ll_card_list);
        cardgroup_item_title = viewHolder.getView(R.id.cardgroup_item_title);
        cardgroup_item_subtitle = viewHolder.getView(R.id.cardgroup_item_subtitle);
        ll_card_more = viewHolder.getView(R.id.ll_card_more);
        ll_top_bigimage = viewHolder.getView(R.id.ll_top_bigimage);
        mTitle.setCompoundDrawables(LedimFunctionUtils.getRandomIcon(mActivity), null, null, null);
        pageIndex = 0;
        mViewHolder = viewHolder;
        mTitle.setText(Html.fromHtml(mCardGroupBean.title));
        if (mCardGroupBean.isUnion()) {
            mGetMore.setVisibility(View.VISIBLE);
            mGetMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //1绑定标签 2绑定频道
                    if (mCardGroupBean.union_type == 1) {
                        //跳转标签页
                        Intent intent = new Intent(mActivity, LedimTagsActivity.class);
                        intent.putExtra(ConstantUtil.ID, mCardGroupBean.union_id);
                        mActivity.startActivity(intent);
                    } else if (mCardGroupBean.union_type == 2) {
                        //跳转频道页
                        Intent intent = new Intent(mActivity, LedimChannelsActivity.class);
                        intent.putExtra(LedimChannelsActivity.CARDID, mCardGroupBean);
                        intent.putExtra(LedimChannelsActivity.CARD_FROM, LedimChannelsActivity.FORM_GET_MORE);
                        mActivity.startActivity(intent);
                        mActivity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
                    }
                }
            });
        } else {
            mGetMore.setVisibility(View.GONE);
        }
        if (needShowResetDataView(mCardGroupBean)) {
            ll_card_more.setVisibility(View.VISIBLE);
            mDrop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDrop.setImageResource(R.anim.data_change);
                    AnimationDrawable animationDrawable = ((AnimationDrawable) mDrop.getDrawable());
                    animationDrawable.stop();
                    animationDrawable.start();
                    pageIndex++;
                    setListData(getNextPageData(mCardGroupBean), mCardGroupBean.id);
                }
            });
            if (mCardGroupBean.style == ConstantUtil.CardGroupStyle.card2) {
                LinearLayout.LayoutParams params =
                        (LinearLayout.LayoutParams) ll_card_list.getLayoutParams();
                params.setMargins(0, 0, 0, 0);
            }
        } else {
            if (mCardGroupBean.style == ConstantUtil.CardGroupStyle.card2) {
                LinearLayout.LayoutParams params =
                        (LinearLayout.LayoutParams) ll_card_list.getLayoutParams();
                params.setMargins(0, 0, 0, DensityUtil.dip2px(mActivity, 10));
            }
            mDrop.setOnClickListener(null);
            ll_card_more.setVisibility(View.GONE);
        }

        if (mCardGroupBean.style == ConstantUtil.CardGroupStyle.card3 ||
                mCardGroupBean.style == ConstantUtil.CardGroupStyle.card6) {
            // 头部专题页 需要设置点击事件以及数据
            ll_top_bigimage.setVisibility(View.VISIBLE);

            if (mCardGroupBean != null && mCardGroupBean.cards != null &&
                    !mCardGroupBean.cards.isEmpty()) {
                final LedimChoiceCardBean card = mCardGroupBean.cards.get(0);
                cardgroup_item_title.setText(Html.fromHtml(card.title));
                cardgroup_item_subtitle.setText(Html.fromHtml(card.subtitle));
                FrescoUtil.loadUrl(card.photo.thumb, mBigImageView);
                ViewGroup.LayoutParams params = mBigImageView.getLayoutParams();
                params.width = mScreenWith - 2 * DensityUtil.dip2px(mActivity, 10);
                params.height = params.width * 4 / 10;
                mBigImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LedimFunctionUtils.jumpTargetActivity(mActivity, card, mCardGroupBean.id);
                    }
                });
            }
        } else {
            if (ll_top_bigimage != null) {
                ll_top_bigimage.setVisibility(View.GONE);
            }
        }
        if (mCardGroupBean.cards != null && !mCardGroupBean.cards.isEmpty()) {
            setListData(getNextPageData(mCardGroupBean), mCardGroupBean.id);
        } else {
            ll_card_list.setVisibility(View.GONE);
        }
    }

    public void setListData(List<LedimChoiceCardBean> cardBeens, String groupId) {
        if (mCardItemViews == null) {
            mCardItemViews = initCardViews(mViewHolder);
        }
        if (mCardItemViews != null && mCardItemViews.size() == getPageSize() && cardBeens != null &&
                cardBeens.size() == getPageSize()) {
            ll_card_list.setVisibility(View.VISIBLE);
            for (int i = 0; i < getPageSize(); i++) {
                mCardItemViews.get(i).setData(cardBeens.get(i), groupId);
            }
        } else {
            ll_card_list.setVisibility(View.GONE);
        }
    }

    private String getEpisodes(String str) {
        String strEnd;
        if (str.length() == 8) {
            strEnd = str.substring(0, 4) + "-" + str.substring(4, 6) + "-" +
                    str.substring(6, str.length());
        } else {
            strEnd = str;
        }
        return strEnd;
    }

    public class BaseCardItemView {

        SimpleDraweeView mPhoto;
        TextView mTitle;
        TextView mRating;
        TextView mEpisodesCount;
        TextView mSubTitle;

        public BaseCardItemView(SimpleDraweeView mPhoto, TextView mTitle, TextView mSubTitle,
                                TextView mRating, TextView mEpisodesCount) {
            this.mPhoto = mPhoto;
            this.mTitle = mTitle;
            this.mRating = mRating;
            this.mEpisodesCount = mEpisodesCount;
            this.mSubTitle = mSubTitle;
            ViewGroup.LayoutParams layoutParams = mPhoto.getLayoutParams();
            layoutParams.height = mPicHeight;
            layoutParams.width = mPicWith;
        }

        public void setData(final LedimChoiceCardBean mCard, final String groupId) {
            if (mCard.link.lastIndexOf("/") + 1 == mCard.link.length()) {
                mCard.link = mCard.link + "0";
            }
            if (mSubTitle != null) {
                mSubTitle.setText(Html.fromHtml(mCard.subtitle));
            }

            if (mCard.photo != null && !TextUtils.isEmpty(mCard.photo.thumb) && mPhoto != null) {
                FrescoUtil.loadUrl(mCard.photo.thumb, mPhoto);
            }
            if (mTitle != null) {
                mTitle.setText(Html.fromHtml(mCard.title.trim()));
            }
            if (mCard.simple_album != null && mCard.simple_album.category != null) {
                Iterator<Integer> iterator = mCard.simple_album.category.keySet().iterator();
                int albumType = -1;
                while (iterator.hasNext()) {
                    albumType = iterator.next();
                }
                if (mRating != null) {
                    if (albumType == ConstantUtil.ChannelType.film) {
                        mRating.setVisibility(View.VISIBLE);
                        mRating.setText(LedimBaseUtils.formatRating(mCard.simple_album.rating));
                    } else {
                        mRating.setVisibility(View.GONE);
                    }
                }
                if (mEpisodesCount != null) {
                    if (albumType == ConstantUtil.ChannelType.film) {
                        mEpisodesCount.setVisibility(View.GONE);
                    } else if (albumType == ConstantUtil.ChannelType.tv ||
                            albumType == ConstantUtil.ChannelType.cartoon) {
                        mEpisodesCount.setVisibility(View.VISIBLE);
                        if (mCard.simple_album.is_end == 1) {
                            mEpisodesCount.setText(mCard.simple_album.episode + "集全");
                        } else {
                            mEpisodesCount.setText("更新至第" + mCard.simple_album.now_episodes + "集");
                        }
                    } else if (albumType == ConstantUtil.ChannelType.variety
                    /*|| albumType == ENUM_CHANNEL_TYPE.SPORT.value()  //暂时不加体育 */) {
                        mEpisodesCount.setVisibility(View.VISIBLE);

                        if (mCard.simple_album.is_end == 1) {
                            //					int episodeCount = Integer.parseInt(getEpisodes(mCard.simple_album.episode));
                            //                    if(episodeCount>0){
                            mEpisodesCount.setText(getEpisodes(mCard.simple_album.episode) + "期全");
                            //                     }
                        } else {
                            //					int nowIssueCount = Integer.parseInt(getEpisodes(mCard.simple_album.now_issue));
                            //					if (nowIssueCount>0) {
                            mEpisodesCount.setText(getEpisodes(mCard.simple_album.now_issue) + "期");
                            //				}
                        }

                    } else if (albumType == ConstantUtil.ChannelType.feed ||
                            albumType == ConstantUtil.ChannelType.music ||
                            albumType == ConstantUtil.ChannelType.entertainment) {
                        mEpisodesCount.setVisibility(View.VISIBLE);
                        mEpisodesCount.setText(LedimBaseUtils.secToTime(mCard.simple_album.duration));
                    } else {
                        mEpisodesCount.setVisibility(View.GONE);
                    }
                }
            } else {
                if (mRating != null) {
                    mRating.setVisibility(View.GONE);
                }
                if (mEpisodesCount != null) {
                    mEpisodesCount.setVisibility(View.GONE);
                }
            }
            mPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LedimFunctionUtils.jumpTargetActivity(mActivity, mCard, groupId);
                }
            });
        }
    }
}
